package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 处理业务异常   收货地址为空   购物车为空
        // 用户id
        Long userId = BaseContext.getCurrentId();
        // 收货地址为空
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            // 抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
//        购物车为空
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectAllByUserId(userId);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            // 抛出业务异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表（1条）插入数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        // 下单时间
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID); // 初始提交订单  支付状态为0  未支付
        orders.setStatus(Orders.PENDING_PAYMENT);   // 订单状态为1 待付款
        orders.setNumber(String.valueOf(System.currentTimeMillis())); // 订单号  使用时间戳
        orders.setPhone(addressBook.getPhone()); // 用户收货手机号
        orders.setUserId(userId);  // 用户id
        orders.setConsignee(addressBook.getConsignee()); // 用户收货地址名字
        // 收获详细地址
        String address = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        orders.setAddress(address); // 用户下单收货地址

        orderMapper.insert(orders);
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //向订单明细表（N条）插入数据
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail(); // 订单明细
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId()); // 订单id
            orderDetailList.add(orderDetail);
        }
        // 批量插入订单明细数据
        orderDetailMapper.insertBatch(orderDetailList);
        // 清空购物车
        shoppingCartMapper.delete(userId);
        // 封装VO返回
        OrderSubmitVO submitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .build();
        return submitVO;

    }


/*
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }*/

    /**
     * 假订单支付
     *
     * @param ordersPaymentDTO
     */
    @Override
    public String fakePayment(OrdersPaymentDTO ordersPaymentDTO) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        String orderNumber = ordersPaymentDTO.getOrderNumber();
        // 根据订单号和userid查询订单信息
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumberAndId(userId, orderNumber);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        return orders.getId() + ":" + orderNumber;
    }

    /**
     * 支付成功回调  响应管理端websocket
     *
     * @param idAndNumber
     */
    @Override
    public void fakePaySuccess(String idAndNumber) {
        // 获取订单id和订单号
        String id = idAndNumber.split(":")[0];
        String number = idAndNumber.split(":")[1];
        // websocket推送消息  type orderId content
        Map map = new HashMap();
        map.put("type", 1); // 1表示来单提醒，2表示客户催单
        map.put("orderId", id);
        map.put("content", "订单号为： " + number);

        String json = JSON.toJSONString(map);
        // 推送消息
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO queryOrders(Long id) {
        Orders orders = orderMapper.selectById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);
        OrderVO orderVo = new OrderVO();
        BeanUtils.copyProperties(orders, orderVo);
        orderVo.setOrderDetailList(orderDetailList);

        return orderVo;
    }

    /**
     * 用户催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.selectById(id);
        // websocket推送消息  type orderId content
        Map map = new HashMap();
        map.put("type", 2); // 1表示来单提醒，2表示客户催单
        map.put("orderId", id);
        map.put("content", "订单号为： " + orders.getNumber());

        String json = JSON.toJSONString(map);
        // 推送消息
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 查询历史订单
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult queryHistoryOrders(Integer page, Integer pageSize, Integer status) {
        OrdersPageQueryDTO orders = new OrdersPageQueryDTO();
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(status);
        PageHelper.startPage(page, pageSize);
        // 查询当前用户的订单
        Page<Orders> pageResult = orderMapper.select(orders);
        List<OrderVO> orderVOS = new ArrayList<>();
        if (pageResult != null && pageResult.size() > 0) {
            for (Orders od : pageResult) {
                // 封装VO
                OrderVO odVO = new OrderVO();
                BeanUtils.copyProperties(od, odVO);
                List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(od.getId());
                odVO.setOrderDetailList(orderDetailList);
                orderVOS.add(odVO);
            }
        }

        return new PageResult(pageResult.getTotal(), orderVOS);
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public String orderCancel(Long id) {
        String sign = "null";
        // 查询订单
        Orders orderDB = orderMapper.selectById(id);
        // 订单不存在
        if (orderDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orderDB.getStatus() > 2) {
            // 联系商家  报错订单异常
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(orderDB.getId());
        orders.setUserId(BaseContext.getCurrentId());

        // 订单处于待接单状态下取消，需要进行退款
        if (orderDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            sign = "cancel";
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(MessageConstant.ORDER_CANCEL_USER);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
        return sign;
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void orderRepetiton(Long id) {
        // 将该单下的订单详情查询出来 再进行复制
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartList.add(shoppingCart);
        }
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 管理端  订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult ordersSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.select(ordersPageQueryDTO);
        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 展示订单状态数量
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 封装VO
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }


    /**
     * 商家接单
     *
     * @param confirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO confirmDTO) {
        Orders orders = new Orders();
        // 更改订单状态
        orders.setId(confirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 派送状态
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        // 更改订单状态
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据ID查询订单
        Orders orders = orderMapper.selectById(ordersRejectionDTO.getId());
        // 判断订单的是否存在且状态为待接单2
        if (orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 查询支付状态是否已支付
        if (orders.getPayStatus().equals(Orders.PAID)) {
            log.info("**********退 款 操 作**************");
            log.info("**********退 款 成 功**************");
            // 支付状态
            orders.setPayStatus(Orders.REFUND);
        }
        // 拒单原因
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        // 订单状态为已取消
        orders.setStatus(Orders.CANCELLED);
        // 设置取消原因
        orders.setCancelReason(MessageConstant.ORDER_CANCEL_ADMIN);
        orders.setCancelTime(LocalDateTime.now());
        orders.setId(ordersRejectionDTO.getId());
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 查询订单是否存在
        Orders orders = orderMapper.selectById(ordersCancelDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 查看订单的支付状态
        if (orders.getPayStatus().equals(Orders.PAID)) {
            // 用户已支付  退款操作
            log.info("**********退 款 操 作**************");
            log.info("**********退 款 成 功**************");
            // 支付状态
            orders.setPayStatus(Orders.REFUND);
        }
        // 取消时间
        orders.setCancelTime(LocalDateTime.now());
        // 取消原因
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        // 订单状态
        orders.setStatus(Orders.CANCELLED); // 已取消
        orderMapper.update(orders);

    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.selectById(id);
        if (orders == null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 更新订单状态,状态转为完成
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }
}
